#!/usr/bin/env python
from __future__ import unicode_literals
from __future__ import absolute_import

import time
from .OrmInterface import host, graph, history, item
from ..utils import type_fail
from ..utils.timestamp import to_timestamp, to_standard


class BaseViewInterface(object):
    def __init__(self, hostid=None, refresh=None, itemid=None, period=720,
                 line_limit=10, stime=None, gname=None,
                 gid=0, _=None):
        self.hostid = type_fail(hostid, int, 3)
        self.refresh = type_fail(refresh, int, None)
        self.itemid = type_fail(itemid, int, None)
        self.period = type_fail(period, int, 720)
        self.line_limit = type_fail(line_limit, int, 10)
        self.stime = type_fail(stime, to_timestamp,
                               time.time() - self.period)
        self.etime = self.stime + self.period
        self.gname = type_fail(gname, str, "None")
        self.gid = type_fail(gid, int, 0)


class Index(BaseViewInterface):
    def get(self):
        items = {}
        # refresh process
        refresh_option = [{'active': False, 'data': None, 'key': 'OFF'},
                          {'active': False, 'data': 5, 'key': '5s'},
                          {'active': False, 'data': 10, 'key': '10s'},
                          {'active': False, 'data': 30, 'key': '30s'},
                          {'active': False, 'data': 60, 'key': '1m'},
                          {'active': False, 'data': 300, 'key': '5m'},
                          {'active': False, 'data': 900, 'key': '15m'},
                          {'active': False, 'data': 1800, 'key': '30m'},
                          {'active': False, 'data': 3600, 'key': '1h'},
                          {'active': False, 'data': 7200, 'key': '2h'},
                          {'active': False, 'data': 86400, 'key': '1d'}]
        if self.refresh:
            for op in refresh_option:
                if op['data'] == self.refresh:
                    op['active'] = True
                    self.refresh = self.refresh * 1000 if self.refresh else \
                        None
            if all(map(lambda x: x['active'] is False,
                       refresh_option)):
                self.refresh, refresh_option[0]['active'] = True, None
        else:
            refresh_option[0]['active'] = True

        items['refresh'] = {'sec': self.refresh, 'option': refresh_option}

        # host info
        h = host()
        items['info'] = h.info(self.hostid)[self.hostid]

        # all host
        items['hosts'] = h.all()

        # host html emement class ative
        for h in items['hosts']:
            if h.hostid == self.hostid:
                h.active = True

        # search time
        items['view_time'] = {'stime': to_standard(self.stime),
                              'etime': to_standard(self.etime)}

        #  process hostid all  graph
        g = graph(limit=self.line_limit, period=self.period, stime=self.stime,
                  etime=self.etime)
        items['graphs'] = {}
        for it in g.get_host(self.hostid):
            gdata = g.highcharts_render_data(it)
            items['graphs'][gdata[0]] = {'data': gdata[2], 'itemids':
                                         map(int, gdata[1])}

        return items


class Ajax(BaseViewInterface):
    def get(self):
        data = {'data': []}
        item_i = item()
        item_orm_object = item_i.get(self.itemid)
        if not item_orm_object:
            return data
        history_i = history(item_i.session, stime=self.stime,
                            period=self.period, limit=self.line_limit)
        history_result = history_i.get(item_orm_object)
        result_sort = sorted(history_result, key=lambda x: x.clock)
        result_data = map(lambda x: [int(x.clock) * 1000,
                                     float('%.2f' % float(x.value))],
                          result_sort[-1:])
        if result_data:
            data['data'] = result_data[0]
        return data
